<template>
    <TheElDialog :title="title" :visible.sync="centerDialogVisible" @close="handleCenterDialogClose" v-bind="$attrs">
        <el-form
            @submit.native.prevent
            ref="formRule"
            :model="form"
            :rules="rules"
            :label-width="isMobile ? '80px' : '120px'"
        >
            <el-form-item prop="depot" label="仓库">
                <el-select v-model="form.depot" filterable clearable placeholder="请选择" style="width: 100%">
                    <el-option v-for="item in optionsDepots" :key="item._id" :label="item.name" :value="item._id">
                    </el-option>
                </el-select>
            </el-form-item>
            <el-form-item prop="datetime" label="提货日期">
                <el-date-picker
                    type="date"
                    placeholder="选择日期"
                    format="yyyy/MM/dd"
                    prefix-icon="false"
                    v-model="form.datetime"
                    :clearable="true"
                    class="form-the-datepicker"
                    style="width: 100%;"
                ></el-date-picker>
            </el-form-item>
            <el-form-item prop="store" label="店铺（间）">
                <el-input
                    type="number"
                    @mousewheel.native.prevent
                    @DOMMouseScroll.native.prevent
                    v-model="form.store"
                    placeholder="请填写店铺（间）"
                ></el-input>
            </el-form-item>
            <el-form-item prop="order" label="每日单量">
                <el-input
                    type="number"
                    @mousewheel.native.prevent
                    @DOMMouseScroll.native.prevent
                    disabled
                    v-model="form.order"
                    placeholder="请填写每日单量"
                ></el-input>
            </el-form-item>
            <el-form-item prop="numHomeProducts" label="首页商品数">
                <el-input
                    type="number"
                    @mousewheel.native.prevent
                    @DOMMouseScroll.native.prevent
                    v-model="form.numHomeProducts"
                    placeholder="请填写首页商品数"
                    @change="onChangeOrderProducts"
                ></el-input>
            </el-form-item>
            <el-form-item prop="numFreshProducts" label="生鲜商品数">
                <el-input
                    type="number"
                    @mousewheel.native.prevent
                    @DOMMouseScroll.native.prevent
                    v-model="form.numFreshProducts"
                    placeholder="请填写生鲜商品数"
                    @change="onChangeOrderProducts"
                ></el-input>
            </el-form-item>

            <el-form-item prop="remark" label="备注">
                <el-input type="textarea" v-model="form.remark" placeholder="请填写备注"></el-input>
            </el-form-item>
            <el-form-item prop="files" label="附件">
                <el-upload
                    :class="[`upload-length--${fileList.length}`]"
                    action="/api/uploads/orders/"
                    :headers="userHeaders"
                    :on-success="onUploadSuccess"
                    :on-error="onUploadError"
                    :on-preview="onPreview"
                    :on-remove="onRemove"
                    :before-upload="beforeImageUpload"
                    :limit="1"
                    :on-exceed="onExceed"
                    :file-list="fileList"
                    drag
                    multiple
                    name="sampleFile"
                    accept="image/png,image/jpg,image/jpeg"
                >
                    <div class="el-upload__text" style="font-size: 12px;padding: 0 4px;">
                        将文件拖到此处，或<em>点击上传</em><br />只能上传png/jpg/jpeg文件，且不超过4MB
                    </div>
                </el-upload>
                <template v-for="item in fileList">
                    <TheImage
                        style="
                            height: 100%;
                            min-height: 400px;
                            width: 270px;
                            min-width: 200px;
                            object-position: 100% 100%;"
                        fit="cover"
                        :key="item.uid"
                        :src="`/api${item.response.data.uri}`"
                        :srcList.sync="srcList"
                    >
                        <div slot="error" class="image-slot">
                            <i class="el-icon-picture-outline"></i>
                        </div>
                    </TheImage>
                </template>

                <!-- <div class="image-wrapper">
                    <div v-for="item in fileList" :key="item.uid" class="image-item">
                        <img v-auth-src="`/api${item.response.data.uri}`" />
                    </div>
                </div> -->
            </el-form-item>
        </el-form>
        <span slot="footer" class="dialog-footer">
            <el-button :disabled="centerDialogLoading" @click="centerDialogVisible = false">取 消</el-button>
            <el-button :loading="centerDialogLoading" type="primary" @click="handleSubmit('formRule')">确 定</el-button>
        </span>
    </TheElDialog>
</template>
<script>
import {postApiList, putApiList} from '@/api/order';
import moment from 'moment';
import TheImage from '@/components/TheImage';
import {beforeImageUpload} from '@/utils/upload-image';
const validatNumber = name => (rule, value, callback) => {
    value = value - 0;

    if ((value !== 0 && value && !Number.isInteger(value)) || value < 0) {
        return callback(new Error(name + '必须为正整数'));
    }

    callback();
};
const validatString = count => (rule, value, callback) => {
    value = (value || '').toString();

    if (value.length >= 0 && value.length <= count) {
        callback();
    } else {
        return callback(new Error(`长度限制为${count}个字符`));
    }
};
export const RULES = {
    datetime: [{required: true, message: '提货日期必填项', trigger: ['change', 'blur']}],
    store: [
        {required: true, message: '店铺必填项', trigger: ['change', 'blur']},
        {validator: validatNumber('店铺数量'), trigger: ['change', 'blur']}
    ],
    order: [
        {required: true, message: '订单必填项', trigger: ['change', 'blur']},
        {validator: validatNumber('订单数量'), trigger: ['change', 'blur']}
    ],
    numHomeProducts: [
        {required: true, message: '首页商品数必填项', trigger: ['change', 'blur']},
        {validator: validatNumber('首页商品数数量'), trigger: ['change', 'blur']}
    ],
    numFreshProducts: [
        {required: true, message: '生鲜商品数必填项', trigger: ['change', 'blur']},
        {validator: validatNumber('生鲜商品数数量'), trigger: ['change', 'blur']}
    ],
    depot: [{required: true, message: '仓库必填项', trigger: ['change', 'blur']}],
    attachments: [{required: false, trigger: ['change', 'blur']}],
    remark: [{validator: validatString(200), trigger: ['change', 'blur']}]
};

export default {
    name: 'center-dialog',
    props: {
        title: {
            type: String,
            default: ''
        },
        visible: {
            type: Boolean,
            default: false
        },
        dataSource: {
            type: Object,
            required: true
        },
        optionsDepots: {
            type: Array,
            default: () => [],
            required: true
        }
    },
    components: {TheImage},
    data() {
        return {
            // 新建弹窗 提交表单中
            centerDialogLoading: false,
            inputStyle: {width: '320px'},
            // 新建表单
            form: {
                id: undefined,
                datetime: new Date(),
                store: undefined,
                order: undefined,
                numHomeProducts: undefined,
                numFreshProducts: undefined,
                depot: '',
                remark: '',
                attachments: undefined
            },
            rules: RULES,
            fileList: [
                // {
                //     status: 'success',
                //     name: '屏幕截图(3).png',
                //     size: 246611,
                //     percentage: 100,
                //     uid: 1636289914735,
                //     raw: {uid: 1636289914735},
                //     response: {
                //         status: 200,
                //         data: {
                //             name: '屏幕截图(3).png',
                //             size: 246611,
                //             md5: '730fead039da4d0ddfa39516bb1d99ed',
                //             mimetype: 'image/png',
                //             uri: '/uploads/orders/730fead039da4d0ddfa39516bb1d99ed.png'
                //         },
                //         msg: 'File uploaded!'
                //     }
                // }
            ],
            srcList: []
        };
    },
    computed: {
        isMobile() {
            return this.$store.getters['app/isMobile'];
        },
        userHeaders() {
            return this.$store.getters['user/headers'];
        },
        isDetail() {
            return typeof this.title === 'string' && this.title.includes('查看');
        },
        centerDialogVisible: {
            get() {
                return this.visible;
            },
            set(val) {
                this.$emit('update:visible', val);
            }
        }
    },
    watch: {
        dataSource: {
            handler(val) {
                this.fileList = val.meta && val.meta.fileList ? [...val.meta.fileList] || [] : [];
                this.form = {
                    ...this.form,
                    ...val,
                    datetime: val.datetime,
                    store: val.store,
                    order: val.order,
                    depot: val.depot,
                    numHomeProducts: val.numHomeProducts,
                    numFreshProducts: val.numFreshProducts,
                    remark: val.remark
                };
                this.$nextTick(() => {
                    this.$refs.formRule && this.$refs.formRule.clearValidate();
                });
            },
            immediate: true
        }
    },
    methods: {
        onUploadError(error) {
            this.$message({showClose: true, type: 'error', message: error.message});
        },
        onUploadSuccess(response, file, fileList) {
            this.fileList = fileList;
        },
        onRemove(file, fileList) {
            this.fileList = [...fileList];
        },
        onPreview(file) {
            console.log(file);
        },
        onExceed(files, fileList) {
            const count = files.length + fileList.length;
            this.$message.warning(`当前限制选择 1 个文件，本次选择了 ${files.length} 个文件，共选择了 ${count} 个文件`);
        },
        beforeImageUpload,
        onChangeOrderProducts() {
            this.form = {
                ...this.form,
                order: (this.form.numHomeProducts || 0) - 0 + ((this.form.numFreshProducts || 0) - 0)
            };
        },
        // 提交表单
        handleSubmit(formName) {
            this.$refs[formName].validate((valid, fields) => {
                if (valid) {
                    const form = this.form;
                    const newItem = {
                        _id: form._id,
                        datetime: new Date(moment(form.datetime).format('YYYY-MM-DD')),
                        store: form.store - 0,
                        order: form.order - 0,
                        numHomeProducts: form.numHomeProducts - 0,
                        numFreshProducts: form.numFreshProducts - 0,
                        meta: {fileList: this.fileList},
                        depot: form.depot,
                        remark: form.remark
                    };

                    if (newItem.order !== newItem.numHomeProducts + newItem.numFreshProducts) {
                    }

                    if (this.title && this.title.includes('添加')) {
                        this.onCreate(newItem);
                    }
                    if (this.title && this.title.includes('编辑')) {
                        this.onPutData(newItem);
                    }
                } else {
                    const first = Object.keys(fields)[0];
                    const items = fields[first] || [];
                    const {message} = items[0] || {};
                    this.$message({showClose: true, type: 'error', message});
                    return false;
                }
            });
        },
        // 创建角色
        onCreate(newItem) {
            this.centerDialogLoading = true;
            postApiList(newItem)
                .then(({data: res}) => {
                    if (res.status === 201) {
                        this.$message({showClose: true, type: 'success', message: '创建成功'});
                        this.centerDialogVisible = false;
                        // this.getList();
                        // 重新更新数据
                        this.$emit('on-ok');
                    } else {
                        throw new Error(res);
                    }
                })
                .catch(error => {
                    const data = error.response && error.response.data;

                    if (data && data.error) {
                        this.$message({showClose: true, type: 'error', message: data.error});
                    } else {
                        this.$message({showClose: true, type: 'error', message: '创建失败'});
                    }
                })
                .finally(() => {
                    this.centerDialogLoading = false;
                });
        },
        // 更新
        onPutData(newItem) {
            this.centerDialogLoading = true;
            putApiList(newItem._id, newItem)
                .then(({data: res}) => {
                    if (res.status === 204) {
                        this.$message({showClose: true, type: 'success', message: '更新成功'});
                        this.centerDialogVisible = false;
                        // this.getList();
                        // 重新更新数据
                        this.$emit('on-ok');
                    } else {
                        throw new Error(res);
                    }
                })
                .catch(error => {
                    this.$message({showClose: true, type: 'error', message: error});
                })
                .finally(() => {
                    this.centerDialogLoading = false;
                });
        },
        // dialog 关闭
        handleCenterDialogClose() {
            // 关闭
            this.$emit('close');
            this.fileList = [];
            this.form = {
                ...this.$options.data().form
                // id: undefined,
                // datetime: '',
                // store: undefined,
                // order: undefined,
                // depot: '',
                // remark: ''
            };
        }
    }
};
</script>
<style lang="scss" scoped>
::v-deep {
    .upload-length--1 {
        .el-upload {
            display: none;
        }
        .el-upload-list__item:first-child {
            margin-top: 0;
        }
    }
    .el-image {
        margin-right: 10px;
        border: 1px solid #d9d9d9;
    }
}
</style>
